<?php

// $Id$

require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');


require_once('tcms_ci_mod.class.php');
require_once($WSC->get_site_inc_dir().'modules/tangra_cms/classes/vpage/tcms_vpage_dbc.class.php');


class TCMS_CI_Mod_DBC extends TCMS_CI_Mod implements I_DB_Storable {
	public function save(DB_Connection $dbc) {
		$ret = false;

		$ret = $this->insert($dbc);
		$this->set_id($ret);
		TCMS_VPage_DBC::update_last_modified_for_ci($dbc, $this->get_modified_by(), $this->get_ci());

		return $ret;
	}


	public function load_by_id(DB_Connection $dbc, $id) {
		tangra_if_not_int_throw_e($id);

		$ret = false;

		$sql = "select ci, ".
						"modified_ts, ".
						"modified_by ".
					"from tcms_ci_mods ".
					"where id = $id";
		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();

			$this->set_id($id);
			$this->set_ci($rez_obj->CI);
			$this->set_modified_ts($rez_obj->MODIFIED_TS);
			$this->set_modified_by($rez_obj->MODIFIED_BY);


			$ret = $id;
		}

		return $ret;
	}



	protected function insert(DB_Connection $dbc) {
		$ret = false;

		$id = $dbc->generate_id('tcms_ci_mods_seq');
		$ci = $this->get_ci();
		$modified_by = $this->get_modified_by();
		$modified_ts = date('Y-m-d H:i:s');

		if ($id) {
			$sql = "insert into tcms_ci_mods (id, ".
									      "ci, ".
									      "modified_ts, ".
									      "modified_by ".
									      ") ".
								"values ".
									      "($id,".
									      "$ci, ".
									      "'$modified_ts', ".
									      "$modified_by ".
									      ")";
			$dbc->execute($sql);
			$ret = $id;
		} else {
			throw new TE_Exception('tcms_ci_mods_seq');
		}

		return $ret;
	}


	public static function load_last_modified_for_ci(DB_Connection $dbc, $ci_id) {
		tangra_if_not_int_throw_e($ci_id);

		$ret = false;
		$sql = "select id from tcms_ci_mods where ci = $ci_id order by id desc";
		$rez = $dbc->execute($sql);
		if (!$rez->is_eod()) {
			$rez_obj = $rez->fetch_object();
			$ret = new TCMS_CI_Mod_DBC();
			$ret->load_by_id($dbc, $rez_obj->ID);
		}

		return $ret;
	}


	public static function load_created_for_ci(DB_Connection $dbc, $ci_id) {
		tangra_if_not_int_throw_e($ci_id);

		$ret = false;
		$sql = "select id from tcms_ci_mods where ci = $ci_id order by id asc";
		$rez = $dbc->execute($sql);
		if (!$rez->is_eod()) {
			$rez_obj = $rez->fetch_object();
			$ret = new TCMS_CI_Mod_DBC();
			$ret->load_by_id($dbc, $rez_obj->ID);
		}

		return $ret;
	}
}